forked from
npmx.dev/npmx.dev
[READ-ONLY]
a fast, modern browser for the npm registry
1import * as v from 'valibot'
2import { PackageNameSchema } from '#shared/schemas/package'
3import { CACHE_MAX_AGE_ONE_HOUR, ERROR_JSR_FETCH_FAILED } from '#shared/utils/constants'
4import type { JsrPackageInfo } from '#shared/types/jsr'
5
6/**
7 * Check if an npm package exists on JSR.
8 *
9 * GET /api/jsr/:pkg
10 *
11 * @example GET /api/jsr/@std/fs → { exists: true, scope: "std", name: "fs", ... }
12 * @example GET /api/jsr/lodash → { exists: false }
13 */
14export default defineCachedEventHandler<Promise<JsrPackageInfo>>(
15 async event => {
16 const pkgPath = getRouterParam(event, 'pkg')
17
18 try {
19 const packageName = v.parse(PackageNameSchema, pkgPath)
20
21 return await fetchJsrPackageInfo(packageName)
22 } catch (error: unknown) {
23 handleApiError(error, {
24 statusCode: 502,
25 message: ERROR_JSR_FETCH_FAILED,
26 })
27 }
28 },
29 {
30 maxAge: CACHE_MAX_AGE_ONE_HOUR,
31 swr: true,
32 name: 'api-jsr-package',
33 getKey: event => {
34 const pkg = getRouterParam(event, 'pkg') ?? ''
35 return `jsr:v1:${pkg.replace(/\/+$/, '').trim()}`
36 },
37 },
38)